package com.wanyu.video.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用同一个buffer copy文件
 */
public class NIOFileCopyUseSameBuffer {

    public static void main(String[] args) throws IOException {


        FileInputStream inputStream = new FileInputStream("C:\\git_code\\netty-in-action-learn\\file\\01.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream("C:\\git_code\\netty-in-action-learn\\file\\02.txt");
        FileChannel outputStreamChannel = outputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);

        while(true){

            // 每次读取都需要清空历史数据并重置坐标
            byteBuffer.clear();
            // inputStreamChannel中的数据写入到Buffer里面
            int read = inputStreamChannel.read(byteBuffer);
            if(read == -1){
                break;
            }
            // 反转buffer坐标
            byteBuffer.flip();

            // 把缓冲区的数据写到channel中
            outputStreamChannel.write(byteBuffer);
        }

        inputStreamChannel.close();
        outputStreamChannel.close();
        inputStream.close();
        outputStream.close();
    }
}
